package com.baffle.socket.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import com.baffle.socket.model.Matching;

public class FileUtils {

	private static String filenameTemp;

	// 文件内容读取
	public static List<Matching> readTxt(String filePath) {
		List<Matching> matchingList = new ArrayList<Matching>();
		try {
			File file = new File(filePath);
			if (file.isFile() && file.exists()) {
				InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String lineTxt = null;
				while ((lineTxt = br.readLine()) != null) {
					String[] lineTxtArr = lineTxt.split(",");
					if (lineTxtArr.length > 0) {

						Matching matching = new Matching();
						String payerCardNo = lineTxtArr[0];
						if (!StringUtils.isEmpty(payerCardNo)) {
							matching.setPayerCardNo(payerCardNo);
						} else {
							continue;
						}
						String amount = lineTxtArr[1];
						if (!StringUtils.isEmpty(amount)) {
							matching.setAmount(amount);
						}

						String stateCode = lineTxtArr[2];
						if (!StringUtils.isEmpty(stateCode)) {
							matching.setStateCode(stateCode);
						}
						String rspCode = lineTxtArr[3];
						if (!StringUtils.isEmpty(rspCode)) {
							matching.setRspCode(rspCode);
						}
						String outTime = lineTxtArr[4];
						if (!StringUtils.isEmpty(outTime)) {
							matching.setOutTime(Integer.valueOf(outTime));
						}

						String isRead = lineTxtArr[5];
						if (!StringUtils.isEmpty(isRead)) {
							matching.setIsRead(isRead);
							if (isRead.equals("isReadN")) {
								matchingList.add(matching);
							}
						}
					}
				}
				br.close();
			} else {
				System.out.println("文件不存在!");
			}
		} catch (Exception e) {
			System.out.println("文件读取错误!");
		}
		return matchingList;
	}

	/**
	 * 创建文件
	 * 
	 * @throws IOException
	 */
	public static boolean creatTxtFile(String path, String fileName) throws IOException {
		boolean flag = false;
		filenameTemp = path + fileName + ".txt";
		File filename = new File(filenameTemp);
		if (filename.exists()) {
			filename.delete();
		}
		filename.createNewFile();
		flag = true;

		return flag;
	}

	/**
	 * 写文件
	 * 
	 * @param newStr
	 *            新内容
	 * @throws IOException
	 */
	public static boolean writeTxtFile(String newStr) throws IOException {
		// 先读取原有文件内容，然后进行写入操作
		boolean flag = false;
		String filein = newStr + "\r\n";
		String temp = "";

		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;

		FileOutputStream fos = null;
		PrintWriter pw = null;
		try {
			// 文件路径
			File file = new File(filenameTemp);
			// 将文件读入输入流
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();

			// 保存该文件原有的内容
			for (int j = 1; (temp = br.readLine()) != null; j++) {
				buf = buf.append(temp);
				// System.getProperty("line.separator")
				// 行与行之间的分隔符 相当于“\n”
				// buf = buf.append(System.getProperty("line.separator"));
				buf = buf.append(System.getProperty("file.encoding"));
			}
			buf.append(filein);

			fos = new FileOutputStream(file);
			pw = new PrintWriter(fos);
			pw.write(buf.toString().toCharArray());
			pw.flush();
			flag = true;
		} catch (IOException e1) {
			// TODO 自动生成 catch 块
			throw e1;
		} finally {
			if (pw != null) {
				pw.close();
			}
			if (fos != null) {
				fos.close();
			}
			if (br != null) {
				br.close();
			}
			if (isr != null) {
				isr.close();
			}
			if (fis != null) {
				fis.close();
			}
		}
		return flag;
	}

	public static void main(String[] args) {
		try {
			String str = "{" + " \"HEAD\": {" + " \"MERCH_ID\": \"101601200000601\","
					+ " \"TRAN_DATETIME\": \"20210601100012\"," + " \"ORDER_ID\": \"20210601100012004954\"" + " },"
					+ " \"BODY\": {" + " \"DATA\": {" + " \"TRAN_CODE\": \"310002\"," + " \"CURRENCY\": \"156\","
					+ " \"AMOUNT\": 50," + " \"PAYER_CARD_NO\": \"6029070123561878\"," + " \"PAYER_NAME\": \"养毅\","
					+ " \"PAYER_ID_TYPE\": \"01\"," + " \"PAYER_ID_CODE\": \"420101198101019779\","
					+ " \"PAYER_PHONE_NO\": \"17700001625\"," + " \"PAYER_OB_BANK_CODE\": \"\","
					+ " \"PAYEE_CARD_NO\": \"749769627778\"," + " \"PAYEE_NAME\": \"开泰银行（中国）有限公司\","
					+ " \"PAYEE_ID_TYPE\": \"\"," + " \"PAYEE_ID_CODE\": \"\"," + " \"PAYEE_PHONE_NO\": \"\","
					+ " \"PAYEE_OB_BANK_CODE\": \"\"," + " \"SMS_NO\": \"\"," + " \"SMS_CODE\": \"\","
					+ " \"DEVICE_IMEI\": \"\"," + " \"IP_USER_ID\": \"\" " + "}" + "}" + "}";
			FileUtils.creatTxtFile("D:\\", "CUPD_RESPONSE");
			FileUtils.writeTxtFile(str);

		} catch (Exception e) {
			e.printStackTrace();
		}

		String filePath = "D:\\matching.txt";

		List<Matching> matchingList = readTxt(filePath);
		System.out.println(matchingList);
	}

	/**
	 * 修改文件内容
	 * 
	 * @param fileUrl
	 * @param payerCardNoAmountFilePaht
	 * @return
	 */
	public static boolean modifyFileContent(String fileUrl, String payerCardNoAmountFilePaht) {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(fileUrl, "rw");
			String line = null;
			// 记住上一次的偏移量
			long lastPoint = 0;
			while ((line = raf.readLine()) != null) {
				String[] lineTxtArr = line.split(",");
				String payerCardNo = lineTxtArr[0];
				String amount = lineTxtArr[1];
				String payerCardNoAmountFile = payerCardNo + "|" + amount;

				String isRead = lineTxtArr[5];
				// 文件当前偏移量
				final long ponit = raf.getFilePointer();
				if (payerCardNoAmountFile.equals(payerCardNoAmountFilePaht)) {
					if (isRead.equals("isReadN")) {
						String str = line.replace("isReadN", "isReadY" + "\n");
						System.err.println(str);
						raf.seek(lastPoint);
						raf.writeBytes(str);
						break;
					}
				}

				lastPoint = ponit;
				System.err.println(lastPoint);

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 文件内容替换
	 * 
	 * @param filePath
	 * @param oldstr
	 * @param newStr
	 */
	private static void autoReplace(String filePath, String oldstr, String newStr) {
		File file = new File(filePath);
		Long fileLength = file.length();
		byte[] fileContext = new byte[fileLength.intValue()];
		FileInputStream in = null;
		PrintWriter out = null;
		try {
			in = new FileInputStream(filePath);
			in.read(fileContext);
			// 避免出现中文乱码
			String str = new String(fileContext, "utf-8");
			str = str.replace(oldstr, newStr);
			out = new PrintWriter(filePath);
			out.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
